package com.achun.ximalayamvvm.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.achun.ximalayamvvm.BaseApplication
import com.achun.ximalayamvvm.PlayerActivity
import com.achun.ximalayamvvm.bean.ProgressInfo
import com.achun.ximalayamvvm.bean.TracksIndex
import com.achun.ximalayamvvm.utils.LogUtil
import com.achun.ximalayamvvm.utils.ToastUtil
import com.achun.ximalayamvvm.view.custom.SingleLiveEvent
import com.ximalaya.ting.android.opensdk.model.PlayableModel
import com.ximalaya.ting.android.opensdk.model.advertis.Advertis
import com.ximalaya.ting.android.opensdk.model.advertis.AdvertisList
import com.ximalaya.ting.android.opensdk.model.track.Track
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager
import com.ximalaya.ting.android.opensdk.player.advertis.IXmAdsStatusListener
import com.ximalaya.ting.android.opensdk.player.service.IXmPlayerStatusListener
import com.ximalaya.ting.android.opensdk.player.service.XmPlayerException
import kotlin.random.Random

class PlayerViewModel private constructor() : ViewModel(), IXmPlayerStatusListener,
    IXmAdsStatusListener {
    private var currentTracks = MutableLiveData<TracksIndex>()
    private var currentTrack = MutableLiveData<Track>()
    private var playMode=PlayerActivity.PlayMode.SORT

    //进度条信息
    private var progressInfo = MutableLiveData<ProgressInfo>()

    //播放状态
    private var isPlaying = MutableLiveData<Boolean>()
    private var currentIndex = 0
    private var player: XmPlayerManager? = null

    init {
        player = XmPlayerManager.getInstance(BaseApplication.getAppContext())
        player?.addPlayerStatusListener(this)
        player?.addAdsStatusListener(this)

    }

    companion object {
        val instace: PlayerViewModel by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            PlayerViewModel()
        }
    }
    //设置播放模式
    fun setPlayMode(playMode:PlayerActivity.PlayMode){
        this.playMode=playMode
    }
    fun getPlayMode(): PlayerActivity.PlayMode {
        return this.playMode
    }
    fun getPlayStatus(): MutableLiveData<Boolean> {
        return isPlaying
    }
    fun getTrack(): MutableLiveData<Track> {
        return currentTrack
    }

    fun getTracks(): MutableLiveData<TracksIndex> {
        return currentTracks
    }

    fun getProgressInfo(): MutableLiveData<ProgressInfo> {
        return progressInfo
    }

    fun setTrack(tracks: List<Track>, startIndex: Int) {
        this.currentTracks.value = TracksIndex(startIndex, tracks)
        this.currentIndex = startIndex
        //设置音乐
        LogUtil.e(this, "设置播放器数据")
        player?.setPlayList(tracks, startIndex)
        LogUtil.e(this, "播放器状态--》${player!!.playerStatus}")
    }

    fun playorPause(): Boolean {
        if (player!!.isPlaying) {
            player?.pause()
            LogUtil.e(this, "点击音乐暂停--")
            return false
        } else {
            LogUtil.e(this, "点击音乐播放--")
            player?.play()
            return true
            player?.run {
                LogUtil.e(this, "当前播放索引--$currentIndex 当前播放歌曲--》${currentTracks.value.toString()}")
            }
        }
    }

    //播放状态监听
    override fun onPlayStart() {
        isPlaying.value = true
        LogUtil.e(this, "开始播放--")
    }

    override fun onPlayPause() {
        isPlaying.value = false
        LogUtil.e(this, "播放暂停--")
    }

    override fun onPlayStop() {
        LogUtil.e(this, "播放停止--")
    }

    override fun onSoundPlayComplete() {
        LogUtil.e(this, "播放完成--")
    }

    //音乐准备好了
    override fun onSoundPrepared() {
        LogUtil.e(this, "初始化--》")
        playorPause()
    }
//切歌
    override fun onSoundSwitch(lastModel: PlayableModel?, currentModel: PlayableModel?) {
        LogUtil.e(this, "播放器切歌--${currentModel.toString()} 当前类型--${currentModel?.kind}")
        var track = currentModel as Track
        LogUtil.e(this, "当前track--${track.toString()}")
        currentTracks.value= TracksIndex(currentIndex,currentTracks.value!!.tracks)
    currentTrack.value = track

    }

    override fun onBufferingStart() {

    }

    override fun onBufferingStop() {

    }

    override fun onBufferProgress(p0: Int) {

    }

    //进度条回调
    override fun onPlayProgress(p0: Int, p1: Int) {
        this.progressInfo.value = ProgressInfo(p0, p1)
//        currentTrack.value = currentTrack.value
//        currentTracks.value=currentTracks.value
        if (p0*100/p1>=99){
            playNext()
        }
    }

    override fun onError(p0: XmPlayerException?): Boolean {
        return false
    }

    //广告监听回调
    override fun onStartGetAdsInfo() {

    }

    override fun onGetAdsInfo(p0: AdvertisList?) {

    }

    override fun onAdsStartBuffering() {

    }

    override fun onAdsStopBuffering() {

    }

    override fun onStartPlayAds(p0: Advertis?, p1: Int) {
        LogUtil.e(this, "广告开始播放")

    }

    override fun onCompletePlayAds() {
        LogUtil.e(this, "广告结束播放")
    }

    override fun onError(p0: Int, p1: Int) {

    }

    //自定义控制方法
    fun playNext() {
        when (playMode) {
            //顺序播放
            PlayerActivity.PlayMode.SORT -> {

                   var tracks = currentTracks.value!!.tracks
                if (currentIndex != tracks.size - 1) {
                    currentIndex++
                    player?.setPlayList(currentTracks.value?.tracks, currentIndex)
                } else {
                    ToastUtil.showToast("已经到底了")
                }
            }
            //随机播放
            PlayerActivity.PlayMode.RANDOM->{
                var randomnum = (0 until currentTracks.value!!.tracks.size).random()
                LogUtil.e(this,"随机数--》$randomnum")
                player?.setPlayList(currentTracks.value?.tracks, randomnum)
            }
            //单曲循环
            PlayerActivity.PlayMode.LOOP->{
                player?.seekToByPercent(0f)
            }
        }
    }
    fun playPre() {

                if (currentIndex != 0) {
                    currentIndex--
                    player?.setPlayList(currentTracks.value?.tracks, currentIndex)
                } else {
                    ToastUtil.showToast("没有上一曲哦")
                }


    }

    fun seekTo(progressByPrecent: Float) {
        player?.seekToByPercent(progressByPrecent)
    }

    fun playByIndex(position: Int) {
        player?.setPlayList(currentTracks.value?.tracks,position)
        currentIndex=position
    }
}


